<script setup lang="ts">
import { ref, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { Delete, Edit, Plus } from "@element-plus/icons-vue";
import MenuForm from "./modules/menuForm.vue";
import { getMenuList, deleteMenu } from "@/api/menu";
import type { Menu } from "@/api/menu";

// 定义标签类型
type TagType = 'success' | 'warning' | 'info' | 'danger' | 'primary';

defineOptions({
  name: "MenuManagement"
});

// 表格数据
const tableData = ref<Menu[]>([]);
const loading = ref(false);

// 弹窗控制
const menuFormVisible = ref(false);
const formType = ref<"add" | "edit">("add");
const currentMenu = ref<Partial<Menu>>({});

// 获取菜单列表
const getMenus = async () => {
  loading.value = true;
  try {
    const res = await getMenuList();
    if (res.code === 0) {
      // 将菜单数据转换为树形结构
      tableData.value = res.data;
    } else {
      ElMessage.error(res.msg || "获取菜单列表失败");
    }
  } catch (error) {
    console.error("获取菜单列表出错:", error);
    ElMessage.error("获取菜单列表失败");
  } finally {
    loading.value = false;
  }
};

// 打开弹窗
const openDialog = (type: "add" | "edit", row?: Menu) => {
  formType.value = type;
  if (type === "add") {
    // 设置默认值
    const parentId = row?.id || 0;

    currentMenu.value = {
      parentId: parentId,
      component: parentId === 0 ? "Layout" : "",
      title: "",
      icon: "",
      rank: 0,
      status: 0,
      auths: []
    };
  } else {
    currentMenu.value = { ...row };
  }
  menuFormVisible.value = true;
};

// 保存菜单
const handleSaveMenu = () => {
  menuFormVisible.value = false;
  getMenus(); // 重新加载列表
};

// 删除菜单
const handleDeleteMenu = async (id: number) => {
  try {
    await ElMessageBox.confirm("确定要删除该菜单吗？删除后不可恢复！", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning"
    });

    const res = await deleteMenu(id);
    if (res.code === 0) {
      ElMessage.success("删除成功");
      getMenus();
    } else {
      ElMessage.error(res.msg || "删除失败");
    }
  } catch (error) {
    if (error !== "cancel") {
      console.error("删除菜单出错:", error);
      ElMessage.error("删除菜单失败");
    }
  }
};

// 获取状态文本和类型
const getStatusInfo = (status: number) => {
  switch (status) {
    case 0:
      return { text: "启用", type: "success" as TagType };
    case 1:
      return { text: "禁用", type: "danger" as TagType };
    default:
      return { text: "未知", type: "info" as TagType };
  }
};

onMounted(() => {
  getMenus();
});
</script>

<template>
  <div>
    <el-card shadow="never" class="box-card">
      <template #header>
        <div class="card-header">
          <span>菜单列表</span>
          <div class="header-buttons">
            <el-button type="primary" :icon="Plus" @click="openDialog('add')">添加菜单</el-button>
          </div>
        </div>
      </template>

      <el-table v-loading="loading" :data="tableData" row-key="id" border :tree-props="{ children: 'children' }"
        default-expand-all>
        <el-table-column prop="title" label="菜单标题" min-width="160">
          <template #default="{ row }">
            <span>{{ row.title || row.meta?.title }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="name" label="路由名称" min-width="120" />
        <el-table-column prop="path" label="路由路径" min-width="140" />
        <el-table-column prop="component" label="组件路径" min-width="140">
          <template #default="{ row }">
            <el-tag v-if="row.component === 'Layout'" type="info" size="small">{{ row.component }}</el-tag>
            <span v-else>{{ row.component }}</span>
          </template>
        </el-table-column>
        <el-table-column label="排序" width="70">
          <template #default="{ row }">
            {{ row.rank || row.meta?.rank || 0 }}
          </template>
        </el-table-column>
        <el-table-column label="状态" width="80">
          <template #default="{ row }">
            <el-tag :type="getStatusInfo(row.status || 0).type" size="small">
              {{ getStatusInfo(row.status || 0).text }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="按钮权限" min-width="120" show-overflow-tooltip>
          <template #default="{ row }">
            <div v-if="(row.auths || row.meta?.auths)?.length > 0">
              <el-tag v-for="auth in (row.auths || row.meta?.auths)" :key="auth" size="small" class="auth-tag">
                {{ auth }}
              </el-tag>
            </div>
            <span v-else-if="row.parentId === 0" class="no-data">父级菜单无按钮权限</span>
            <span v-else class="no-data">-</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="280" fixed="right">
          <template #default="{ row }">
            <div class="button-group">
              <el-button type="primary" size="small" :icon="Plus" @click="openDialog('add', row)">
                添加
              </el-button>
              <el-button type="success" size="small" :icon="Edit" @click="openDialog('edit', row)">
                编辑
              </el-button>
              <el-button type="danger" size="small" :icon="Delete" @click="handleDeleteMenu(row.id)">
                删除
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 菜单表单 -->
    <MenuForm v-model:visible="menuFormVisible" :menu="currentMenu" :type="formType" @save="handleSaveMenu" />
  </div>
</template>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-buttons {
  display: flex;
  gap: 10px;
}

.menu-tag {
  margin-left: 8px;
}

.auth-tag {
  margin-right: 5px;
}

.no-data {
  color: #909399;
  font-size: 12px;
}
</style>